package com.simen.hellobytes.socket;

import java.io.IOException;
import java.net.*;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/5/25 11:00
 * @modify 修改者 Simen
 */
public class UDPClient extends AbstractSocketClient {

    private String serverIp;
    private int port;

    private DatagramSocket datagramSocket;

    private byte[] messageBytes;

    private boolean isRunning = false;

    public UDPClient(String serverIp, int port) {
        this.serverIp = serverIp;
        this.port = port;
    }

    public UDPClient(String serverIp, int port, byte[] messageBytes) {
        this.serverIp = serverIp;
        this.port = port;
        this.messageBytes = messageBytes;
    }

    public void sendMessage() {
        isRunning = true;

        try {
            datagramSocket = new DatagramSocket();

            if (messageBytes != null) {
                InetAddress address = InetAddress.getByName(serverIp);

                DatagramPacket datagramPacket = new DatagramPacket(messageBytes, messageBytes.length, address, port);

                datagramSocket.send(datagramPacket);
            }

            if (receiveBackMsg) {
                byte[] recBuf = new byte[bufSize];
                DatagramPacket recPacket = new DatagramPacket(recBuf, recBuf.length);

                datagramSocket.receive(recPacket);

                recBytes = new byte[recPacket.getLength()];

                System.arraycopy(recPacket.getData(), recPacket.getOffset(), recBytes, 0, recBytes.length);

                if (transform != null) {
                    new UDPClient(transform.getServerIp(), transform.getPort(), transform.transform(recBytes)).sendMessage();
                }
            }

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeImmediately();
        }

        isRunning = false;
    }

    public void closeImmediately() {
        if (datagramSocket != null) {
            if (datagramSocket.isConnected()) {
                datagramSocket.disconnect();
            }

            datagramSocket.close();
            datagramSocket = null;
        }
    }

    public byte[] getMessageBytes() {
        return messageBytes;
    }

    public void setMessageBytes(byte[] messageBytes) {
        this.messageBytes = messageBytes;
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

}
